import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Link,withRouter } from 'react-router-dom'
import { actionCreators } from './store';
import api from '../../api/api.js'
import { 
  HeaderWrapper,
  Logo,
  Menu,
  SearchWrapper,
  InfoWrapper

} from './style'

import { Input, Modal, Button, Form, Row, Col, AutoComplete, Select} from 'antd';

const Search = Input.Search;
const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;

class HeaderCom extends Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      grade: '1',
      // 登录信息
      loginName: '',
      password: '',
      singUp: {
        phone: ''
      },
      // 注册信息
      url: this.props.history.location.pathname,
      form: null
    }
  }
  componentDidMount() {
    if(this.props.login) {
      this.props.showCart()
    }
  }

  componentWillUpdate() {
    let url = this.props.history.location.pathname
    if(url !== this.state.url) {
      this.setState({
        url
      })
    }
  }

//   GetUrlRelativePath(){
// 　　var url = document.location.toString();
// 　　var arrUrl = url.split("//");
// 　　var start = arrUrl[1].indexOf("/");
// 　　var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

// 　　if(relUrl.indexOf("?") != -1){
// 　　　　relUrl = relUrl.split("?")[0];
// 　　}
// 　　return relUrl;
// 　}
  showModal = (str) => {
    // this.setState({
    //   visible: true
    // });
    debugger
    this.props.changeShowLogin(true)
    this.props.changeType(str)
  }

  handleCancel = () => {
    console.log('Clicked cancel button');
    this.props.changeShowLogin(false)
    // this.setState({
    //   visible: false,
    // });
  }

  singUp = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        debugger
        this.props.singUp({
          time: this.props.sms.get('time'),
          md5: this.props.sms.get('data'),
          ...values
        })
      }
    });
  }

  sendSms (mode) {
    debugger
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.sendSms({
          phone: values.phone,
          mode
        })
      }
    });
  }

  toSearch(params) {
    this.props.search(params) 
    if(this.props.location.pathname = '/') {
      this.props.history.push({ pathname : '/course' ,query : { search: params} })
    }
  }

  renderLogin() {
    return (
      <div>
        <p style={{marginTop: "30px",fontSize: "16px", marginBottom: "16px"}}>小提示：新用户请先注册使用(北仑区内学生直接使用身份证号登录,密码默认123456)，老用户请输入手机号或者身份证密码登录</p>
        <div style={{display: "flex",marginBottom: "30px",fontSize: "16px"}}>
          <div style={{width: "80px"}}>账号：</div> <Input  size="large" placeholder="请输入手机号或身份证号" value={this.state.loginName}  onChange={(e)=> (this.setState({loginName: e.target.value}))}/>
        </div>
        <div style={{display: "flex",fontSize: "16px"}}>
          <div style={{width: "80px"}}>密码：</div> <Input  size="large" placeholder="请输入密码" type="password" value={this.state.password} onChange={(e)=> (this.setState({password: e.target.value}))}/>
        </div>
        <div style={{marginTop: "20px", textAlign: "center"}}>
          <Button style={{marginBottom: "10px"}} type="primary" size="large" block onClick={
            () => {
              // debugger
              let str = this.props.location.pathname
              debugger
              let seach  = this.props.location.query ? this.props.location.query.search : ''
              this.props.Login(this.state, str, seach)
              // this.props.showCart()
              // this.setState({visible: false})
              this.props.changeShowLogin(false)
              // if(this.props.location.pathname.indexOf('courseitem')!=-1) {
              //   setTimeout(() => {
              //     this.props.getCourseList({
              //       lessonId: this.props.location.pathname.split('/')[2]
              //     })
              //   }, 1000);
              // }
            }
          }>登录</Button>
          <a onClick={()=> (this.props.changeType('singUp'))}>还没账号，去注册</a> | <a href="#" onClick={()=> (this.props.changeType('find'))}>忘记密码?</a>
        </div>
      </div>
    )
  }

  renderRegistered() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 8 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <p style={{marginTop: "30px",fontSize: "16px", marginBottom: "16px"}}>小提示：新用户请先注册使用(北仑区内学生直接使用身份证号登录,密码默认123456)，老用户请输入手机号或者身份证密码登录</p>
        <Form {...formItemLayout}>
          <Form.Item label="姓名">
            {
              getFieldDecorator('name', {
                rules: [
                  {
                    required: true, message: "姓名不能为空！"
                  }
                ]

              })(<Input placeholder="请输入姓名" />)
            }
          </Form.Item>
          <Form.Item label="年级">
            {
               getFieldDecorator('grade', {
                initialValue: "一年级"
              })(<Select
              >
                <Option value="一年级">一年级</Option>
                <Option value="二年级">二年级</Option>
                <Option value="三年级">三年级</Option>
                <Option value="四年级">四年级</Option>
                <Option value="五年级">五年级</Option>
                <Option value="六年级">六年级</Option>
                <Option value="初一">初一</Option>
                <Option value="初二">初二</Option>
                <Option value="初三">初三</Option>
                <Option value="高一">高一</Option>
                <Option value="高二">高二</Option>
                <Option value="高三">高三</Option>
              </Select>)
            }

          </Form.Item>
          <Form.Item label="密码">
            {
              getFieldDecorator('password', {
                rules: [
                  {
                    required: true, message: "密码不能为空！"
                  },
                  {
                    min: 6, message: "密码不能少于6位数！"
                  }
                ]

              })(<Input type="password" placeholder="请输入密码" />)
            }
          </Form.Item>
          <Form.Item label="手机号">
            {
              getFieldDecorator('phone', {
                rules: [
                  {
                    required: true, message: "手机号不能为空！"
                  },
                  {
                    len: 11, message: "手机格式不正确"
                  }
                ]

              })(<Input placeholder="请输入手机号"/>)
            }
          </Form.Item>
          <Form.Item label="验证码">
            <div style={{display: "flex"}}> 
              {
                 getFieldDecorator('verifyCode', {

                })(<Input placeholder="请输入验证码" />)
              }
              &nbsp;&nbsp;
            <Button type="primary"  onClick={this.sendSms.bind(this, 0)} disabled={this.props.smsCount === 0 ? false: true}>{this.props.smsCount===0 ? '获取验证码': (this.props.smsCount)}</Button>
            </div>
          </Form.Item>
        </Form>
        <div style={{textAlign: "center", width: "90%", margin: "0 auto"}}>
          <Button style={{marginBottom: "10px"}} type="primary" onClick={this.singUp} block size="large">注册</Button>
          <a onClick={()=> (this.props.changeType('login'))}>已有账号，去登录</a>
        </div>
      </div>
    )
  }
  componentWillReceiveProps(props) {
    console.log('len', this.props.cartLen, props)
  }

  renderFind(){
    const formItemLayout = {
      labelCol: {
        xs: { span: 8 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Form {...formItemLayout}>
          <Form.Item label="新密码">
            {
              getFieldDecorator('password', {
                rules: [
                  {
                    required: true, message: "密码不能为空！"
                  },
                  {
                    min: 6, message: "密码不能少于6位数！"
                  }
                ]

              })(<Input type="password" placeholder="请输入密码" />)
            }
          </Form.Item>
          <Form.Item label="手机号">
            {
              getFieldDecorator('phone', {
                rules: [
                  {
                    required: true, message: "手机号不能为空！"
                  },
                  {
                    len: 11, message: "手机格式不正确"
                  }
                ]

              })(<Input placeholder="请输入手机号"/>)
            }
          </Form.Item>
          <Form.Item label="验证码">
            <div style={{display: "flex"}}> 
              {
                 getFieldDecorator('verifyCode', {

                })(<Input placeholder="请输入验证码" />)
              }
              &nbsp;&nbsp;
            <Button type="primary"  onClick={this.sendSms.bind(this, 1)} disabled={this.props.smsCount === 0 ? false: true}>{this.props.smsCount===0 ? '获取验证码': (this.props.smsCount)}</Button>
            </div>
          </Form.Item>
        </Form>
        <div style={{textAlign: "center", width: "90%", margin: "0 auto"}}>
          <Button style={{marginBottom: "10px"}} type="primary" onClick={this.findPassword.bind(this)} block size="large">确定</Button>
          <a onClick={()=> (this.props.changeType('login'))}>已有账号，去登录</a>
        </div>
      </div>
    )
  }

  findPassword() {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.findPassword({
          time: this.props.sms.get('time'),
          md5: this.props.sms.get('data'),
          ...values
        })
      }
    });
  }

  render() {
    const { confirmLoading } = this.state;
    const visible = this.props.visible
    return (
      <div style={{width: '100%', backgroundColor: '#fff'}}>
      <HeaderWrapper>
        <Link to="/">
        <Logo />
        </Link>
        <Menu>
          <li>
            <Link to="/" className={this.state.url ==='/' ? 'active' : ''}  onClick={()=> (this.setState({url: '/'}))}>首页</Link>
          </li>
          {
            this.props.login ? <li>
            <Link to="/mycourse" className={this.state.url ==='/mycourse' ? 'active' : ''} onClick={()=>(this.setState({url: '/mycourse'}))}>我的课程</Link>
          </li> : null
          }
          
          <li>
            <Link to="/course" className={this.state.url ==='/course' ? 'active' : ''} onClick={()=> (this.setState({url: '/course'}))}>课程中心</Link>
          </li>
        </Menu>
        <SearchWrapper>
          <Search
            placeholder="请输入搜索内容"
            onSearch={value => this.toSearch(value)}
            style={{ width: 250 }}
          />
        </SearchWrapper>
        <InfoWrapper>
          {
            this.props.login ?  
              <li>
                <i className="iconfont icon-gouwuche icon"></i>&nbsp;
                <Link to="/cart">
                    购物车
                    { 
                      this.props.cartLen.size ? <span className="cart-num">{this.props.cartLen.size}</span>:null
                    }
                </Link>
              </li> : null
          }
          <li>
            <i className="iconfont icon-gerenxinxi icon"></i>
            {
              this.props.login ? <Link to="/person">{this.props.login.get('name')}</Link> : <a style={{color: "#8BCA31"}} onClick={this.showModal.bind(this,'login')}>请登录</a>
            }
          </li>
          <li>
            {
              this.props.login ? <a>{this.props.login.get('stuGradeStr')}</a> : <a style={{color: "#8BCA31"}} onClick={this.showModal.bind(this, 'singUp')}>注册</a>
            }
          </li>
          {
            this.props.login ?  <li onClick={this.props.ClearUser}><a style={{color: '#8BCA31'}}>退出</a></li> : null
          }
        </InfoWrapper>
        <Modal
          visible={visible}
          width={600}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
          footer={false}
        >
          {
            this.props.showType === 'login'? this.renderLogin() : (this.props.showType === 'find' ? this.renderFind() : this.renderRegistered())
          }
        </Modal>
      </HeaderWrapper>
      </div>
    )
  }
} 

const mapState = (state) => {
  return {
    login: state.getIn(['header', 'login']),
    showType: state.getIn(['header', 'showType']),
    sms: state.getIn(['header', 'sms']),
    cartLen: state.getIn(['header', 'cartList', 'list']),
    visible: state.getIn(['header', 'showLogin']),
    smsCount: state.getIn(['header', 'smsCount'])
  }
}

const mapDispatch = (dispatch)=> ({
  Login(obj, str) {
    dispatch(actionCreators.Login(
      {
        loginName: obj.loginName, 
        password: obj.password
      },
      str
    ))
  },
  ClearUser() {
    localStorage.clear();
    sessionStorage.clear();
    dispatch(actionCreators.ClearUser())
  },
  sendSms(obj) {
    dispatch(actionCreators.sendSms(obj))
  },
  singUp(obj) {
    dispatch(actionCreators.singUp(obj))
  },
  changeType(obj) {
    dispatch(actionCreators.changeShowType(obj))
  },
  showCart() {
    dispatch(actionCreators.getCartList())
  },
  search(obj) {
    dispatch(actionCreators.search(obj))
  },
  changeShowLogin(params) {
    dispatch(actionCreators.changeShowLogin(params))
  },
  findPassword(params) {
    dispatch(actionCreators.findPassword(params))
  }
  // getCourseList(params){
  //   dispatch(getCourseDescript(params))
  // }
})

export default connect(mapState, mapDispatch)(Form.create({ name: 'registered' }) (withRouter(HeaderCom)))